<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title id="pageTitle">友情链接 - 福利云API</title>
  <link rel="icon" type="image/png" sizes="56x56" href="FreeAPI.png" />
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" />
  <link rel="stylesheet" href="css/style.css" />
</head>
<body>

<div data-include="nav.html"></div>

  <!-- 页面主体内容 -->
  <div class="container">
    <a href="/" class="doc-back">
      <i class="fas fa-arrow-left"></i> 返回首页
    </a>

    <div class="header-box">
      <h1 class="main-title" id="linksTitle">友情链接</h1>
      <div class="notice-banner">
        <p id="linksSubtitle">不止是免费的API，更是一个免费的公益福利云</p>
        <p>本站不定期检测友链，添加后请勿下架本站友链</p>
      </div>
    </div>
    
    <div class="tip-box">
      <p class="links-stats" id="linksStats">正在统计友链数量...</p>
    </div>

    <div class="links-container" id="linksContainer">
      <!-- 友情链接将通过JS动态加载 -->
      <div class="loader" id="loader">
        <div class="loader-spinner"></div>
        <p>正在加载友链数据...</p>
      </div>
    </div>

    <div data-include="footer.html"></div>
  </div>

  <!-- 浮动按钮 -->
  <div class="floating-buttons">
    <button id="theme-toggle" class="floating-btn" aria-label="切换主题" onclick="themeToggleHandler()">
      <i class="fas fa-moon"></i>
    </button>
    <button id="scroll-to-top" class="floating-btn" aria-label="返回顶部">
      <i class="fas fa-arrow-up"></i>
    </button>
  </div>
  
  <!-- 内联主题切换脚本 -->
  <script>
    // 内联主题切换函数
    function themeToggleHandler() {
      console.log('内联主题切换函数被调用');
      
      const htmlElement = document.documentElement;
      const currentTheme = htmlElement.getAttribute('data-theme') || 'light';
      const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
      
      console.log('当前主题:', currentTheme, '切换为:', newTheme);
      
      // 设置主题
      htmlElement.setAttribute('data-theme', newTheme);
      localStorage.setItem('theme', newTheme);
      
      // 更新图标
      const themeIcon = document.querySelector('#theme-toggle i');
      if (themeIcon) {
        themeIcon.className = newTheme === 'dark' ? 'fas fa-sun' : 'fas fa-moon';
      }
      
      // 按钮动画
      const themeToggleBtn = document.getElementById('theme-toggle');
      if (themeToggleBtn) {
        themeToggleBtn.style.transform = 'scale(0.8)';
        setTimeout(() => {
          themeToggleBtn.style.transform = '';
        }, 300);
      }
      
      // 强制重新应用链接卡片样式
      setTimeout(() => {
        const linkCards = document.querySelectorAll('.link-card');
        linkCards.forEach(card => {
          // 强制重新应用样式
          card.style.backgroundColor = '';
          
          const linkInfo = card.querySelector('.link-info');
          if (linkInfo) linkInfo.style.backgroundColor = '';
          
          const linkActions = card.querySelector('.link-actions');
          if (linkActions) linkActions.style.backgroundColor = '';
        });
      }, 50);
    }
    
    // 页面加载时应用保存的主题
    document.addEventListener('DOMContentLoaded', function() {
      const savedTheme = localStorage.getItem('theme');
      const systemPrefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
      const currentTheme = savedTheme || (systemPrefersDark ? 'dark' : 'light');
      
      // 应用主题
      document.documentElement.setAttribute('data-theme', currentTheme);
      
      // 更新图标
      const themeIcon = document.querySelector('#theme-toggle i');
      if (themeIcon) {
        themeIcon.className = currentTheme === 'dark' ? 'fas fa-sun' : 'fas fa-moon';
      }
    });
  </script>

  <!-- 脚本 -->
  <script src="js/main.js" defer></script>
  <script src="js/toproll.js" defer></script>
  <script>
    document.addEventListener('DOMContentLoaded', async () => {
      await loadIncludes();
      initializeTopNav();
      loadLinksData();
    });

    async function loadLinksData() {
      try {
        // 显示加载中
        document.getElementById('loader').style.display = 'block';
        
        // 加载友链数据
        const response = await fetch('config/links.json');
        if (!response.ok) throw new Error(`服务器响应错误: ${response.status}`);
        
        const data = await response.json();
        
        // 更新标题和副标题
        if (data.title) document.getElementById('linksTitle').textContent = data.title;
        if (data.subtitle) document.getElementById('linksSubtitle').textContent = data.subtitle;
        
        // 渲染友链列表
        renderLinks(data.links || []);
        
      } catch (error) {
        console.error('加载友链数据失败:', error);
        const errorHtml = `
          <div class="error-panel" style="text-align: center;">
            <h2 class="error-title"><i class="fas fa-exclamation-triangle"></i> 加载数据失败</h2>
            <p>${error.message}</p>
            <div class="controls" style="margin-top: 20px;">
              <button class="btn" onclick="loadLinksData()">
                <i class="fas fa-redo"></i> 重试
              </button>
            </div>
          </div>
        `;
        
        document.getElementById('linksContainer').innerHTML = errorHtml;
      } finally {
        // 隐藏加载中
        document.getElementById('loader').style.display = 'none';
      }
    }
    
    function renderLinks(links) {
      const linksContainer = document.getElementById('linksContainer');
      const linksStats = document.getElementById('linksStats');
      
      // 更新统计信息 - 从JSON中获取实际数量
      linksStats.textContent = `共收录了 ${links.length} 个平台友链`;
      
      if (!links.length) {
        linksContainer.innerHTML = `
          <div style="text-align: center; padding: 30px; width: 100%;">
            <i class="fas fa-info-circle" style="font-size: 2rem; color: var(--gray);"></i>
            <p style="margin-top: 10px; color: var(--gray);">暂无友链数据</p>
          </div>
        `;
        return;
      }
      
      // 渲染友链卡片
      linksContainer.innerHTML = links.map(link => {
        // 为每个链接创建一个唯一ID，用于更新状态
        const linkId = `link-${Math.random().toString(36).substr(2, 9)}`;
        const visitId = `visit-${Math.random().toString(36).substr(2, 9)}`;
        
        return `
          <div class="link-card">
            <div class="link-card-inner">
              <div class="link-image">
                <img src="${link.image}" alt="${link.name}" onerror="this.src='img/01.png'">
              </div>
              <div class="link-info">
                <h3 class="link-name">${link.name}</h3>
                <p class="link-desc">${link.description || '这家伙很懒但是啥都没留下'}</p>
              </div>
              <div class="link-actions">
                <a href="${link.url}" target="_blank" class="link-btn visit-btn" id="${visitId}">
                  <i class="fas fa-eye"></i> 访问
                </a>
                <a href="javascript:void(0)" class="link-btn check-btn" id="${linkId}">
                  <i class="fas fa-spinner fa-spin"></i> 检测中
                </a>
              </div>
            </div>
          </div>
        `;
      }).join('');
      
      // 检测每个链接的状态
      links.forEach((link, index) => {
        const linkId = document.querySelectorAll('.check-btn')[index].id;
        checkLinkStatus(link.url, linkId);
      });
    }
    
    // 检测链接状态的函数
    async function checkLinkStatus(url, linkId) {
      const linkElement = document.getElementById(linkId);
      if (!linkElement) return;
      
      try {
        // 使用fetch API检测链接是否可访问
        // 注意：由于浏览器的同源策略限制，这种方法可能不适用于所有链接
        // 实际生产环境中，应该使用服务器端API来检测链接状态
        const controller = new AbortController();
        const timeoutId = setTimeout(() => controller.abort(), 5000); // 5秒超时
        
        const response = await fetch(url, { 
          mode: 'no-cors', // 使用no-cors模式避免CORS错误
          signal: controller.signal,
          method: 'HEAD' // 只获取头信息，减少数据传输
        });
        
        clearTimeout(timeoutId);
        
        // 链接正常
        linkElement.innerHTML = `<i class="fas fa-check-circle"></i> 正常`;
        linkElement.classList.add('status-ok');
        linkElement.classList.remove('status-error');
      } catch (error) {
        // 链接异常
        linkElement.innerHTML = `<i class="fas fa-times-circle"></i> 异常`;
        linkElement.classList.add('status-error');
        linkElement.classList.remove('status-ok');
      }
    }
  </script>
</body>
</html> 
